import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import adminRoutes from './modules/admin'
import visitorRoutes from './modules/visitor'

// 定义路由白名单
const whiteList = ['/login', '/register', '/404']

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login/index.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register/index.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  // 404 页面
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '页面未找到', requiresAuth: false }
  },
  ...adminRoutes,
  ...visitorRoutes,
  // 未匹配路由重定向到 404
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 博物馆导览系统` : '博物馆导览系统'
  
  // 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  const hasToken = userInfo.token
  
  // 不需要登录的页面直接放行
  if (!to.meta.requiresAuth) {
    next()
    return
  }
  
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录用户重定向到对应首页
      next(userInfo.role === 'ADMIN' ? '/admin/dashboard' : '/visitor/home')
    } else {
      // 验证用户权限
      if (to.meta.role && to.meta.role !== userInfo.role) {
        // ElMessage.error('无权访问该页面')
        next(userInfo.role === 'ADMIN' ? '/admin/dashboard' : '/visitor/home')
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // ElMessage.warning('请先登录')
      next({ 
        path: '/login', 
        query: { redirect: to.fullPath }
      })
    }
  }
})

export default router 